<template>
    <el-row class="point-type-info-form" type="flex" justify="center">
        <el-col>
            <el-form label-position="top" :model="editForm" :rules="editFormRules" ref="editForm" @submit.native.prevent>
                <input type="hidden"  v-model="editForm.id">
                <el-form-item label="点位类别名称：" prop="pointTypeName">
                    <el-input v-model="editForm.pointTypeName" auto-complete="off" placeholder="请输入点位类别"></el-input>
                </el-form-item>
                <el-form-item label="检查项类型："  style="padding-bottom: 20px;">
                    <el-button class="add-tab-btn" type="primary" @click="addTab()">添加检查内容</el-button>
                    <el-tabs v-model="activeTabsValue" type="card" closable @tab-remove="removeTab">
                      <el-tab-pane
                        v-for="item in editableTabs2"
                        :key="item.name"
                        :label="item.title"
                        :name="item.name">
                        <el-form-item label="内容名称：" :prop="'content_' + item.name">
                            <el-input v-model="item.content"></el-input>
                        </el-form-item>
                        <el-form-item class="check-type" label="检查项类型：">
                          <el-radio-group v-model="item.optionType" size="medium">
                            <el-radio :label="0">默认配置</el-radio>
                            <el-radio :label="1">单选项</el-radio>
                          </el-radio-group>
                        </el-form-item>
                        <template v-if="item.optionType">
                          <el-form-item
                            v-for="(attrObj, attrindex) in item.attr.length>0?item.attr:item.attr.push({option:'',isOk:false}, {option:'',isOk:true})"
                            :key="attrObj.id">
                            <el-row :gutter="12">
                              <el-col :span="14">
                                <el-input v-model="attrObj.option" placeholder="请输入检查项"></el-input>
                              </el-col>
                              <el-col :span="7">
                                  <el-checkbox @change="attrObj.isOk=!attrObj.isOk" :checked="attrObj.isOk?false:true">设置为不合格</el-checkbox>
                              </el-col>
                              <el-col :span="3">
                                  <el-button v-if="attrindex===0" type="primary" icon="el-icon-plus" @click.prevent="addDomain(item.attr)"><!--新增--></el-button>
                              </el-col>
                              <el-col :span="3">
                                  <el-button v-if="attrindex > 1" type="danger" icon="el-icon-delete" @click.prevent="removeDomain(item.attr,attrindex)"><!--删除--></el-button>
                              </el-col>
                            </el-row>
                          </el-form-item>
                        </template>
                      </el-tab-pane>
                    </el-tabs>
                </el-form-item>
                <el-form-item label="类别图片：">
                  <el-upload
                      :action="QINIUUPLOADURL"
                      :multiple="true"
                      ref="upload"
                      list-type="picture-card"
                      :data="qiniuData"
                      :on-success="handleAvatarSuccess"
                      :on-remove="handleRemovePic"
                      :on-error="handleError"
                      :before-upload="beforeAvatarUpload"
                      :on-preview="$imgPreview"
                      :file-list="qiniuData.fileList" 
                      accept="image/gif,image/jpeg,image/jpg,image/bmp,image/png">
                      <i class="el-icon-plus"></i>
                  </el-upload>
                </el-form-item>
                <el-form-item label-width="0" class="verifyidentity-button">
                    <el-button  round @click="closeDialog()">取消</el-button>
                    <el-button type="primary" round @click="savePointType('editForm')">确定</el-button>
                </el-form-item>
            </el-form>
        </el-col>
    </el-row>
</template>

<script>
import util from '@/utils/util'
import { qnToken} from '@/api/api'
import {addInspectPointType} from '@/api/inspect'

export default {
  name:'PointTypeMaintain',
  props: {
    editInfo: {
        type: Object,
        required: false
    },
    closeDialog: {
        type: Function,
        required: true
    },
  },
  data() {
    return {
        qiniuData:{//上传图片携带的参数
            token : "",
            key : "",
            fileList:[],
        },
        defaultImg: this.GLOBAL.defaultImg,
        util:util,
        activeTabsValue: "1",
        editableTabs2: [],
        editForm: {
            id: '',
            orgId:this.$store.state.userinfo.org.id,
            pointTypeName: '',
            picUrl:'',
            createAccount:this.$store.state.userinfo.accountName,
            updateAccount:this.$store.state.userinfo.accountName,
            contents:''
        },
        editFormRules: {
            pointTypeName: [
                { required: true, message: '请输入点位类别名称', trigger: 'blur' },
            ],
        },
    }
  },
  created() {
      let infoObj = this.editInfo
      if(infoObj.id) {//编辑
          this.editForm.id = infoObj.id
          this.editForm.orgId = infoObj.orgId
          this.editForm.pointTypeName = infoObj.pointTypeName
          this.editForm.picUrl = infoObj.picUrl
          infoObj.picUrl?$.each(infoObj.picUrl.split(','),(index,url)=>{
            this.qiniuData.fileList.push({
                name:'现场图片'+index,
                url:url
            })
          }):''
          this.editForm.createAccount = infoObj.createAccount
          if(infoObj.contentList.length > 0) {
            $.each(infoObj.contentList,(index,obj)=>{
              this.editableTabs2.push({
                title: '检查内容'+(index+1),
                name: index+1+"",
                content:obj.content,
                attr:obj.attr,
                optionType:obj.optionType,//0默认 1单选
                sort:obj.sort
              })
            })
          } else {
            // 默认添加一个检查项
            this.addTab()
          }
      } else {
        // 默认添加一个检查项
        this.addTab()
      }
      this.getToken();//获取token
  },
  methods: {
    validateContent(rule, value, callback) {
      let that = this
      let index = Number(rule.field.split('_')[1]) - 1
      if(!that.editableTabs2[index].content) {
        callback(new Error('请输入内容名称'))
        that.activeTabsValue = String(rule.field.split('_')[1])
      } else {
        callback()
      }
    },
    addDomain(attrArr){
        return attrArr.push({
            option:'',
            isOk:true
        })
    },
    removeDomain(attrArr,attrindex){
        return attrArr.splice(attrindex, 1)
    },
    getToken(){  //上传之前获取 token
      qnToken({}).then((result) => {
        this.qiniuData.token= result.data
      })
    },
    beforeAvatarUpload: function(file){//重命名和校验
      var fielLocal = file.name.split(".")
      var fielType = "." + fielLocal[fielLocal.length-1]
      var fielLocalName = fielLocal[0]
      this.qiniuData.key = 'ilink_'+new Date().getTime()+fielType   
      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      const isLt20M = file.size / 1024 / 1024 < 20;
      if (!isJPG && !isPNG) {
        this.$message.error("图片只能是 JPG/PNG 格式!");
        return false;
      }
      if (!isLt20M) {
        this.$message.error("图片大小不能超过 20MB!");
        return false;
      }
    },
    handleAvatarSuccess: function(res, file, fileList) {//上传成功
      this.qiniuData.fileList = fileList;
    },
    handleRemovePic: function(file, fileList) {//删除成功
      this.qiniuData.fileList = fileList;
    },
    handleError: function(res) {
      this.$message({
        message: "上传失败",
        duration: 2000,
        type: "warning"
      });
    },
    addTab() {
        let newTabName = this.editableTabs2.length>0?(this.editableTabs2[this.editableTabs2.length - 1]['sort']+ 1+''):'1'
        this.editableTabs2.push({
          title: '检查内容'+newTabName,
          name: newTabName,
          content:"",
          attr:[],
          optionType:0,//0默认 1单选
          sort:parseInt(newTabName)
        });
        // 添加校验规则
        this.editFormRules['content_'+newTabName] = [
          { required: true, validator: this.validateContent, trigger: 'change' }
        ]
        this.activeTabsValue = newTabName;
    },
    removeTab(targetName) {
        let tabs = this.editableTabs2;
        let activeName = this.activeTabsValue;
        if(tabs.length > 1) {
          if (activeName === targetName) {
            tabs.forEach((tab, index) => {
              if (tab.name === targetName) {
                let nextTab = tabs[index + 1] || tabs[index - 1];
                if (nextTab) {
                  activeName = nextTab.name;
                }
              }
            });
          }
          this.activeTabsValue = activeName
          this.editableTabs2 = tabs.filter(tab => tab.name !== targetName)
        } else {
          this.$message({
            message: '检查内容至少存在一条',
            type: 'warning'
          })
        }
    },
    checkTypeValidate() {
      let that = this
      let flag = true
      let data = that.editableTabs2

      for(let i=0, len=data.length; i < len; i++) {
        if(data[i].optionType == 1 && flag) {
          // 是否存在两种不同结果（合格、不合格）
          let hasDiffResult = false
          for(let j=0, num=data[i].attr.length; j < num; j++) {
            // 检查项为空
            if(data[i].attr[j].option == '') {
              that.activeTabsValue = String(i+1)
              that.$message({
                type: 'warning',
                message: `请输入“${data[i].title}”中的检查项`
              })
              flag = false
              return false
            } else if(data[i].attr[j].isOk != data[i].attr[0].isOk) {
              hasDiffResult = true
            }
          }
          if(!hasDiffResult) {
            that.activeTabsValue = String(i+1)
            that.$message({
              type: 'warning',
              message: `请正确设置“${data[i].title}”中的状态，需同时存在合格、不合格两种不同状态`
            })
            flag = false
            return false
          }
        }
      }

      return flag
    },
    savePointType(formName) {
        // 阻止事件冒泡
        event.stopPropagation()
        let that = this
        that.$refs[formName].validate((valid) => {
            if (valid) {
              // 检测是否有合格和不合格两种情况
              if(that.checkTypeValidate()) {
                let parames = that.editForm
                parames.picUrl = util.ilinkArrHandle.getqiniuPicUrlArr(this.qiniuData.fileList).toString()
                parames.contents = JSON.stringify(that.editableTabs2);
                console.log(parames);
                addInspectPointType(parames).then(res => {
                    that.$message({
                        message: '保存成功！',
                        type: 'success'
                    })
                    console.log(res);
                    that.closeDialog(true)
                });
              }
            } else {
              return false
            }
        });
    },
  }
}
</script>
<style lang="scss">
.point-type-info-form {
  .add-tab-btn {
    position: absolute;
    top: -45px;
    right: 0;
  }
  .check-type {
    margin-top: 10px;
    .el-form-item__label {
      float: left;
    }
  }
  .el-row {
    margin-bottom: 10px; 
    
  }
}
</style>
